package com.xc.h05.controller;

import com.xc.h05.util.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("file")
//@CrossOrigin
public class FileController {
    String rootPath = "C:/sfzy/";// C:/sfzy/
    @PostMapping("upload")
    public R upload(MultipartFile file) throws IOException {
        //1.判断是否为空
        if(file.isEmpty()){
            return R.fail();
        }
        //2.获取文件名
        String fileName = file.getOriginalFilename();
        fileName = UUID.randomUUID().toString().replace("-","")+"-"+fileName;

        SimpleDateFormat format1 = new SimpleDateFormat("yyyyMM");
        String dirName = format1.format(new Date());

        File dirFile = new File(rootPath,dirName);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //组成上传的路径
//        fileName = rootPath+fileName;
        //复制上传到相应路径
        file.transferTo(new File(dirFile,fileName));

        String realPath = dirName+"/"+fileName;
        //返回结果
        return R.ok(realPath);
    }
    /*@PostMapping("upload2")
    public R upload2(MultipartFile file) throws IOException {
        //判断文件是否存在
        if (file.isEmpty()){
            return R.ok("fail");
        }
        //获取文件名
        String filename = file.getOriginalFilename();
        filename = UUID.randomUUID().toString().replace("-","")+"-"+filename;

        SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
        String dirname = format.format(new Date());

        File dirFile = new File(rootPath,dirname);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }

        file.transferTo(new File(dirFile,filename));
        String realPath1 = dirname+"/"+filename;
        return R.ok(realPath1);// 3.143/169

    }*/
    @RequestMapping("downLoad")
    public void downLoad(String fileName, HttpServletResponse response) throws IOException {

        FileInputStream fis = new FileInputStream(new File(rootPath,fileName));
        response.setHeader("Content-Disposition","filename="+ URLEncoder.encode(fileName,"UTF-8")); //预览/下载
        ServletOutputStream out = response.getOutputStream();
        IOUtils.copy(fis,out);
//        System.out.println("下载成功");
        out.close();
        fis.close();
    }
}
